<template>
  <el-form
    label-width="80px"
    label-position="left"
    :rules="rules"
    :model="directorysForm"
  >
    <el-form-item label="所属学科" v-if="!id">
      <el-select v-model="directorysForm.subjectID" placeholder="请选择">
        <el-option
          :label="item.label"
          :value="item.value"
          :key="index"
          v-for="(item, index) in subjectList"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="目录名称" prop="directoryName">
      <el-input
        v-model="directorysForm.directoryName"
        placeholder="请选择"
      ></el-input>
    </el-form-item>
    <el-form-item>
      <span class="footer">
        <el-button @click="$emit('close-dialog')">取 消</el-button>
        <el-button type="primary" @click="handelDirectory">确 定</el-button>
      </span>
    </el-form-item>
  </el-form>
</template>

<script>
import { simple as subjectlist } from '../../api/hmmm/subjects'
import { update, add } from '@/api/hmmm/directorys'
export default {
  props: ['editParams', 'id'],
  data() {
    return {
      rules: {
        directoryName: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ]
      },
      directorysForm: {
        subjectID: this.editParams.subjectID,
        directoryName: this.editParams.directoryName
      },
      subjectList: []
    }
  },
  created() {
    this.getSubject()
    console.log(this.editParams)
  },
  methods: {
    async getSubject() {
      // 获取学科
      if (this.id) return
      try {
        const { data: res } = await subjectlist(this.directorysForm)
        this.subjectList = res
      } catch (err) {
        console.log(err)
      }
    },
    async handelDirectory() {
      // 确认修改和新增
      try {
        if (this.editParams.subjectID) {
          // 修改
          console.log(this.directorysForm)
          // 学科id,表单中没有,就说明是从学科跳转的
          this.directorysForm.subjectID =
            this.directorysForm.subjectID || this.id * 1
          this.directorysForm.id = this.editParams.id
          const { data: res } = await update(this.directorysForm)
          console.log(res)
        } else {
          // 新增
          this.directorysForm.subjectID =
            this.directorysForm.subjectID || this.id * 1
          const { data: res } = await add(this.directorysForm)
          console.log(res)
        }
        this.$message.success('操作成功')
      } catch (err) {
        console.log(err)
        this.$message.error('操作失败')
      }
      this.$emit('close-dialog')
    }
  }
}
</script>

<style scoped lang="scss">
.footer {
  position: absolute;
  right: 0px;
}
.el-select,
el-input {
  width: 100%;
}
</style>
